// src/store/user.js
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { userApi } from "@/api/user";
import { resetRouter } from "@/router";

export const useUserStore = defineStore("user", () => {
  const token = ref(localStorage.getItem("token") || "");
  const userInfo = ref(null);
  const dynamicRoutes = ref([]); // 服务端返回的动态路由列表

  const isLogin = computed(() => !!token.value);

  // 登录
  const login = async (loginData) => {
    const response = await userApi.login(loginData);
    token.value = response.data.token;
    userInfo.value = response.data.userInfo;
    // 服务端返回的动态路由
    dynamicRoutes.value = response.data.userInfo.dynamicRoutes || [];
    localStorage.setItem("token", token.value);
    return response;
  };

  // 登出
  const logout = () => {
    token.value = "";
    userInfo.value = null;
    dynamicRoutes.value = [];
    localStorage.removeItem("token");
    resetRouter(); // 重置动态路由
  };

  // 获取用户信息和动态路由
  const getUserInfo = async () => {
    const response = await userApi.getUserInfo();
    userInfo.value = response.data;
    // 服务端返回的动态路由
    dynamicRoutes.value = response.data.dynamicRoutes || [];
    return response;
  };

  return {
    token,
    userInfo,
    dynamicRoutes,
    isLogin,
    login,
    logout,
    getUserInfo,
  };
});
